package event

import (
	"fmt"
	"git.supremind.info/product/box/vehicle/internal/dto"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

type HttpService struct {
	db *gorm.DB
}

func InitHttp(r *gin.RouterGroup, db *gorm.DB) {
	s := &HttpService{
		db: db,
	}
	router := r.Group("/events")
	{
		router.GET("", s.eventList)
		router.GET("/count", s.count)
	}
}

func (s *HttpService) eventList(c *gin.Context) {
	users := make([]EventAlarm, 0)
	Db := s.db
	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.Query("page_size"))

	if age, isExist := c.GetQuery("age"); isExist == true {
		ageInt, _ := strconv.Atoi(age)
		Db = Db.Where("age = ?", ageInt)
	}

	if num, isExist := c.GetQuery("num"); isExist == true {
		numInt, _ := strconv.Atoi(num)
		Db = Db.Where("num = ?", numInt)
	}

	if name, isExist := c.GetQuery("name"); isExist == true {
		Db = Db.Where("name = ?", name)
	}

	if page > 0 && pageSize > 0 {
		Db = Db.Limit(pageSize).Offset((page - 1) * pageSize)
	}

	if err := Db.Find(&users).Error; err != nil {
		fmt.Println(err.Error())
	}

	result := dto.Result{
		Code:    http.StatusOK,
		Message: "请求成功",
		Data:    users,
	}
	c.JSON(http.StatusOK, result)
}

func (s *HttpService) consts(c *gin.Context) {
	c.JSON(http.StatusOK, "SSSS")
}

func (s *HttpService) count(c *gin.Context) {
	var count int64
	s.db.Model(&EventAlarm{}).Count(&count)
	result := dto.Result{
		Code:    http.StatusOK,
		Message: "请求成功",
		Data:    count,
	}
	c.JSON(http.StatusOK, result)
}

func (s *HttpService) delHisData(c *gin.Context) {
	c.JSON(http.StatusOK, "SSSS")
}
